<?php 

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\model\Member;
use app\admin\model\Povertymember;
use app\admin\model\Image;

use think\Request;

class Povertywork extends Base
{

    public function _initialize() {
        parent::_initialize();
        $this->model = 'povertywork';

        /*$defaultWhere = $this->getDefaultWhere();
        $defaultWhere['isDelete'] = ['neq', 1];
        $this->defaultWhere = $defaultWhere;*/
        switch ($this->admin->type) {
            case 0:
                $this->defaultWhere = ['a.isDelete' => ['neq', 1]];
                break;
            case 1:
                $this->defaultWhere = ['a.cityId' => $this->admin->cityId, 'a.isDelete' => ['neq', 1]];
                break;
            case 2:
                $this->defaultWhere = ['a.xianId' => $this->admin->xianId, 'a.isDelete' => ['neq', 1]];
                break;
            case 3:
            case 6:
                $this->defaultWhere = ['a.townId' => $this->admin->townId, 'a.isDelete' => ['neq', 1]];
                break;
            case 4:
                $this->defaultWhere = ['a.villageId' => $this->admin->villageId, 'a.isDelete' => ['neq', 1]];
                break;
            default:
                $this->defaultWhere = ['a.isDelete' => ['neq', 1]];
                break;
        }

        $this->searchFields = [
            'aidingName' => [
                'label'     => '帮扶人',
                'field'     => 'aidingName',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];
    }

    public function index() {
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }

            $where['b.isDelete'] = 2;
            $join = [
                ['__MEMBER__ b', 'b.id = a.povertymemberId'],
            ];
            $field = 'a.*, b.name as povertyName';
            $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->order($order)->select();
            foreach ($list as &$item) {
                // 扶贫干部
                $item['aidingName'] = Member::where('id', $item['aidingId'])->value('name');

                // 图集
                $imgList = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->order('sorting ASC')->select();
                $item->imgList = $imgList;
            }
            $count = $model->alias('a')->where($where)->join($join)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return $this->view->fetch($this->indexView, [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    public function add(Request $request) {
        return parent::add($request);
    }

    public function addPost(Request $request, $redirect = ''){
        $data = $request->param();
        $povertymemberId = $data['povertymemberId'];

        $data['id'] = Helper::getUUID();
        if(isset($data['imgIds'])) {
            foreach ((Array)$data['imgIds'] as $key => $val) {
                Image::where('id', $val)->update(['relatedId' => $data['id'], 'relatedTable' => $this->model, 'tag' => 'imglist', 'sorting' => $key]);
            }
        }
        $member = Member::where('id', $povertymemberId)->field('cityId,xianId,townId,villageId')->find();
        $data['cityId'] = $member['cityId'];
        $data['xianId'] = $member['xianId'];
        $data['townId'] = $member['townId'];
        $data['villageId'] = $member['villageId'];
        $data['time'] = strtotime($data['time']);
        $data['createDate'] = time();
        $data['updateDate'] = time();
        $data['createOper'] = $this->admin->id;
        $data['updateOper'] = $this->admin->id;
        $model = model($this->model);
        $result = $model->save($data);
        
        if ($result !== false) {
            return $this->success('添加成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('添加失败');
        }
    }

    public function edit(Request $request) {
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        // 扶贫干部 // TODO 不能用 Povertywork 表里的 povertypartyId（扶贫干部）字段，因为贫困户的 aidingId 会发生改变
        //$aidingId = Povertymember::where(['memberId' => $info->povertymemberId])->value('aidingId');

        $this->assign('area', $this->getArea($info));
        $this->assign('imgList',[]);
        $this->assign('imgcount',0);

        return $this->view->fetch('edit', [
            'info' => $info
        ]);
    }

    public function editPost(Request $request, $redirect = '') {
        $data = $request->param();
        $povertymemberId = $data['povertymemberId'];
        if(isset($data['imgIds'])) {
            foreach ((Array)$data['imgIds'] as $key => $val) {
                Image::where('id', $val)->update(['relatedId' => $data['id'], 'relatedTable' => $this->model, 'tag' => 'imglist', 'sorting' => $key]);
            }
        }
        $member = Member::where('id', $povertymemberId)->field('cityId,xianId,townId,villageId')->find();
        $data['cityId'] = $member['cityId'];
        $data['xianId'] = $member['xianId'];
        $data['townId'] = $member['townId'];
        $data['villageId'] = $member['villageId'];
        $data['time'] = strtotime($data['time']);
        $data['updateDate'] = time();
        $data['updateOper'] = $this->admin->id;
        $model = model($this->model);
        $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

        if ($result !== false) {
            return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('保存失败');
        }
    }

    public function delete() {
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');

        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }
        $result = $model->where('id', $id)->update(['isDelete' => 1]);
        if($result !== false) {
            $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功！', url('admin/' . strtolower($this->model) . '/index'));
        }

        return $this->error('删除失败！', url('admin/' . strtolower($this->model) . '/index'));
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['cityId']) && $filter['cityId']){
                $where['a.cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['a.xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['a.townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['a.villageId'] = $filter['villageId'];
            }
            if(isset($filter['organizationId']) && $filter['organizationId']){
                $where['a.organizationId'] = $filter['organizationId'];
            }

            if(isset($filter['aidingName']) && $filter['aidingName']){
                // 帮扶人
                $aidingIds = Member::where(['name' => ['like', '%'.$filter['aidingName'].'%']])->column('id');

                $aidingIds && $where['a.aidingId'] = ['in', $aidingIds];
            }
        }

        return $where;
    }
}